package com.gxa.customer.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.commons.R;
import com.gxa.customer.redis.AccessLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 拦截恶意访问接口 - 逻辑处理
 */
@Component
public class BrushProofHandler implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    private static final String REDIS_KEY_PREFIX= "api::interface";
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是不是方法
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            // 判断方法中是否有此注解
            AccessLimit accessLimit = method.getMethodAnnotation(AccessLimit.class);
            if (accessLimit != null) {
                // 时间限制大小
                long seconds = accessLimit.seconds();
                // 最大次数
                long maxCount = accessLimit.maxCount();
                // 时间单位
                TimeUnit timeUnit = accessLimit.timeUnit();
                // 接口名称
                String apiName = accessLimit.apiName();
                // 获取调用者ip
                String ip = request.getHeader("x-forwarded-for");
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
				// redis的完整key
                String redisKey = REDIS_KEY_PREFIX + "::" + apiName + ":: " + ip;


                Integer count =0;
                Object o = redisTemplate.opsForValue().get(redisKey);
                if (o!=null){
                    count = Integer.valueOf(o.toString());
                }
                if (count == 0) {
                    redisTemplate.opsForValue().set(redisKey, "1", seconds, timeUnit);
                    System.out.println(2222);
                } else if (count < maxCount) {
                    // 在时间允许范围内
                    count = count +1 ;
                    redisTemplate.opsForValue().set(redisKey, count.toString(), seconds, timeUnit);
                } else {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    R<Object> r = new R<>();
                    r.setCode(200);
                    r.setMsg("请你注意你的行为！不要频繁访问！");
                    response.getWriter().write(JSONObject.toJSONString(r));
                    return false;
                }
            }
        }
        return true;
    }
}